<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
	xmlns:q="livcos.org/ns/query"
  xmlns:u="livcos.org/ns/cosmos/update"
  xmlns:job="livcos.org/ns/process/job"
  xmlns:f="livcos.org/ns/xslt/function"
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  exclude-result-prefixes="q u job f xs">

  <xsl:import href="data.xsl" />
	
	<xsl:output cdata-section-elements="q:cache" xmlns:q="livcos.org/ns/query"/>
  
  <xsl:param name="ref"/>
	
  <xsl:template match="/">
  	<xsl:variable name="q" select="f:entity($ref, .)"/>
  	<xsl:variable name="d">
  		<xsl:apply-templates select="$q" mode="query"/>
  	</xsl:variable>
  	<xsl:variable name="data">
  		<cache time="{current-dateTime()}" xmlns="livcos.org/ns/query">
  			<xsl:copy-of select="$q/q:cache/@valid"/>
  			<u:cdata>
  				<xsl:value-of select="f:serialize($d/*)"/></u:cdata>
  		</cache>
  	</xsl:variable>
  	<u:context ref="{f:object-id($q)}" scope="content">
    	<xsl:choose>
    		<xsl:when test="$q/q:cache">
    			<u:replace node="{$q/@id}" select="q:cache">
    				<u:namespace prefix="q" uri="livcos.org/ns/query"/>
    				<xsl:sequence select="$data"/>
    			</u:replace>
    		</xsl:when>
    		<xsl:otherwise>
    			<u:insert node="{$q/@id}">
    				<xsl:sequence select="$data"/>
    			</u:insert>
    		</xsl:otherwise>
    	</xsl:choose>
    </u:context>
  </xsl:template>
  
</xsl:stylesheet>
